<template>
  <div class="login-container">
    <el-form
      :model="form"
      ref="ruleForm"
      :rules="rules"
      label-width="80px"
      class="login-form"
    >
      <h2 class="login-title">登录演示</h2>

      <el-form-item label="账户" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//import { login, getUserInfo } from "@/api/login";

export default {
  methods: {
    // 注意：按钮上调用的函数名要一致 submitForm
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$store.dispatch("Login", this.form).then(response => {
            if (response.flag) {
              // 获取用户信息
              this.$store.dispatch("GetUserInfo").then(response => {
                if (response.flag) {
                  // 前往首页
                  this.$router.push("/");
                } else {
                  this.$message({
                    message: response.message,
                    type: "warning"
                  });
                }
              });
            } else {
              this.$message({
                message: response.message,
                type: "warning"
              });
            }
          });
        } else {
          console.log("验证失败！");
          return false;
        }
      });
    }
  },
  data() {
    return {
      form: {},
      // 表单校验
      rules: {
        username: [
          // 对应el-form-item 的 prop 值
          { required: true, message: "帐号不能为空", trigger: "blur" }
        ],
        password: [{ required: true, message: "密码不能为空", trigger: "blur" }]
      }
    };
  }
};
</script>

<style>
.login-form {
  width: 350px;
  margin: 12% auto;
  background-color: RGBA(255, 255, 255, 0.8);
  padding: 28px;
  border-radius: 20px;
}

.login-container {
  position: absolute;
  width: 100%;
  height: 100%;
  background-size: 100% 100%;
  background-color: lightslategray;
}

.login-title {
  color: #303133;
  text-align: center;
}
</style>
